package com.tjl.foodapp;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShopListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShopListFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public ShopListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShopListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShopListFragment newInstance(String param1, String param2) {
        ShopListFragment fragment = new ShopListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    //页面元素声明

    RecyclerView rv_shoplist_center;
    //上下文
    Context context;
    //请求队列
    RequestQueue queue;
    //循环列表数据源列表
    ArrayList<Shop> list = new ArrayList<Shop>();
//适配器类
    class MyAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view =  LayoutInflater.from(context).inflate(R.layout.shop_item,null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
          ViewHolder viewHolder = (ViewHolder)holder;
          Shop shop = list.get(position);
          viewHolder.tx_shopname_shopitem.setText(shop.getShopname());
          viewHolder.tx_address_shopitem.setText(shop.getAddress());
          viewHolder.star_level_shopitem.setRating(shop.getLevel());
        getImageByURL(Utils.urlBase+"image/"+shop.getPic()+".jpg"
                ,viewHolder.img_shop_shopitem);
        //给图片按钮添加点击事件
        viewHolder.img_shop_shopitem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //准备数据
                Bundle bundle = new Bundle();
                bundle.putInt("shop_id",shop.getShop_id());
                bundle.putString("shopname",shop.getShopname());
                bundle.putString("prePage","shoplist");
                changeFragment(new FoodListFragment(),bundle,"foodlist");
            }
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }
    class ViewHolder extends RecyclerView.ViewHolder{
        ImageButton img_shop_shopitem;
        TextView tx_shopname_shopitem;
        RatingBar star_level_shopitem;
        TextView tx_address_shopitem;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            img_shop_shopitem = itemView.findViewById(R.id.img_shop_shopitem);
            tx_shopname_shopitem = itemView.findViewById(R.id.tx_shopname_shopitem);
            star_level_shopitem = itemView.findViewById(R.id.star_level_shopitem);
            tx_address_shopitem = itemView.findViewById(R.id.tx_address_shopitem);

        }
    }
}
MyAdaper adaper;
    //子页面管理器
    FragmentManager manager;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shop_list, container, false);

        rv_shoplist_center = view.findViewById(R.id.rv_shoplist_center);
        context = this.getActivity();
        queue = Volley.newRequestQueue(context);
         adaper = new MyAdaper();
         manager = this.getActivity().getSupportFragmentManager();
         rv_shoplist_center.setAdapter(adaper);
         rv_shoplist_center.setLayoutManager(new LinearLayoutManager(context));
         getArrayList(Utils.urlBase+"and_getShopList.do");
        return view;
    }
    //获取网络图片
    public void getImageByURL(String url,ImageButton imageButton){
        int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
        int cachSize = maxMemory/8;
        LruCache<String, Bitmap> lruCache = new LruCache<String,Bitmap>(cachSize);
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String s) {
                return lruCache.get(s);
            }

            @Override
            public void putBitmap(String s, Bitmap bitmap) {
                 lruCache.put(s,bitmap);
            }
        };
        ImageLoader loader = new ImageLoader(queue,imageCache);
        ImageLoader.ImageListener listener
                = ImageLoader.getImageListener(imageButton,
                R.drawable.ic_launcher_background,
                R.drawable.ic_launcher_foreground);
        loader.get(url,listener);
    }
    //获取网络数据
    public void getArrayList(String url){
        Response.Listener listener1 = new Response.Listener(){

            @Override
            public void onResponse(Object o) {
                list = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),new TypeToken<ArrayList<Shop>>(){}.getType());
                adaper.notifyDataSetChanged();
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonArrayRequest(url,listener1,listener2);
        queue.add(request);
    }
    public void changeFragment(Fragment fragment,Bundle bundle,String tag){
        //清空子页面栈
        for(int i=0,count = manager.getBackStackEntryCount();i<count;i++){
            manager.popBackStack();
        }
        //创建一个子页面的事务，以便切换子页面
        FragmentTransaction transaction = manager.beginTransaction();
        //设置子页面的初始化参数
        fragment.setArguments(bundle);
        //切换子页面，让子页面显示到主页面的指定位置
        transaction.add(R.id.linear_fragment,fragment);
        //给栈中的子页面一个标签
        transaction.addToBackStack(tag);
        //提交事务
        transaction.commit();
    }
}